package com.finger.forest;

import android.graphics.drawable.BitmapDrawable;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.core.content.ContextCompat;

import com.esri.arcgisruntime.ArcGISRuntimeEnvironment;
import com.esri.arcgisruntime.geometry.GeodeticCurveType;
import com.esri.arcgisruntime.geometry.Geometry;
import com.esri.arcgisruntime.geometry.GeometryEngine;
import com.esri.arcgisruntime.geometry.LinearUnit;
import com.esri.arcgisruntime.geometry.LinearUnitId;
import com.esri.arcgisruntime.geometry.Point;
import com.esri.arcgisruntime.geometry.PointCollection;
import com.esri.arcgisruntime.geometry.Polyline;
import com.esri.arcgisruntime.geometry.SpatialReferences;
import com.esri.arcgisruntime.location.LocationDataSource;
import com.esri.arcgisruntime.mapping.ArcGISMap;
import com.esri.arcgisruntime.mapping.Basemap;
import com.esri.arcgisruntime.mapping.view.Callout;
import com.esri.arcgisruntime.mapping.view.DefaultMapViewOnTouchListener;
import com.esri.arcgisruntime.mapping.view.Graphic;
import com.esri.arcgisruntime.mapping.view.GraphicsOverlay;
import com.esri.arcgisruntime.mapping.view.LocationDisplay;
import com.esri.arcgisruntime.mapping.view.MapView;
import com.esri.arcgisruntime.symbology.PictureMarkerSymbol;
import com.esri.arcgisruntime.symbology.SimpleLineSymbol;
import com.finger.forest.base.BaseActivity;
import com.finger.forest.base.BaseView;
import com.finger.forest.base.CommonKey;
import com.finger.forest.base.SystemConfig;
import com.finger.forest.http.presenter.RegisterPresenter;
import com.finger.forest.utils.ClickUtils;
import java.util.Arrays;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 测距
 */
public class MeasureLineActivity extends BaseActivity<RegisterPresenter> implements BaseView {

    private static final String TAG = "MeasureLineActivity";

    /**
     * 返回
     */
    @BindView(R.id.btn_back)
    ImageView backIv;

    /**
     * 清空
     */
    @BindView(R.id.btn_right)
    TextView clearTv;

    private MapView mMapView;

    private final LinearUnit mUnitOfMeasurement = new LinearUnit(LinearUnitId.METERS);

    GraphicsOverlay graphicsOverlay = new GraphicsOverlay();

    Point start = null;
    Graphic endLocation = null;
    Graphic path = null;

    private LocationDisplay mLocationDisplay;

    @Override
    protected int setView() {
        return R.layout.activity_measure_line;
    }

    @Override
    protected void receiveData() {

    }

    @Override
    protected void initializeView() {
        mMapView = findViewById(R.id.mapView);
        setupMap();

        //定位当前位置
        setupLocationDisplay(false);

        mMapView.getGraphicsOverlays().add(graphicsOverlay);

        //初始化地图
        initMapView();

        mMapView.setOnTouchListener(new DefaultMapViewOnTouchListener(this, mMapView) {
            @Override
            public boolean onSingleTapConfirmed(MotionEvent motionEvent) {
                android.graphics.Point clickLocation = new android.graphics.Point(Math.round(motionEvent.getX()),
                        Math.round(motionEvent.getY()));
                Point mapPoint = mMapView.screenToLocation(clickLocation);
                if (start == null){
                    start = (Point) GeometryEngine.project(mapPoint, SpatialReferences.getWgs84());
                    BitmapDrawable bitmapDrawable = (BitmapDrawable) ContextCompat.getDrawable(MeasureLineActivity.this, R.drawable.icon_measure_point);
                    PictureMarkerSymbol locationMarker = new PictureMarkerSymbol(bitmapDrawable);
                    locationMarker.setOffsetY(13);
                    Graphic startLocation = new Graphic(start, locationMarker);
                    graphicsOverlay.getGraphics().add(startLocation);
                } else{
                    final Point destination = (Point) GeometryEngine.project(mapPoint, SpatialReferences.getWgs84());
                    endLocation.setGeometry(destination);
                    // create a straight line path between the start and end locations
                    PointCollection points = new PointCollection(Arrays.asList(start, destination), SpatialReferences.getWgs84());
                    Polyline polyline = new Polyline(points);
                    // densify the path as a geodesic curve and show it with the path graphic
                    Geometry pathGeometry = GeometryEngine
                            .densifyGeodetic(polyline, 1, mUnitOfMeasurement, GeodeticCurveType.GEODESIC);
                    path.setGeometry(pathGeometry);
                    // calculate the path distance
                    double distance = GeometryEngine.lengthGeodetic(pathGeometry, mUnitOfMeasurement, GeodeticCurveType.GEODESIC);

                    TextView calloutContent = new TextView(getApplicationContext());
                    calloutContent.setTextColor(getResources().getColor(R.color.colorBlue));
                    calloutContent.setSingleLine();
                    calloutContent.setText(String.format("%.2f", distance) + " 米");

                    final Callout callout = mMapView.getCallout();
                    callout.setLocation(mapPoint);
                    callout.setContent(calloutContent);
                    Callout.Style style = new Callout.Style(MeasureLineActivity.this, R.xml.callout_style_line);
                    callout.setStyle(style);
                    callout.show();
                }
                return true;

            }
        });
    }

    //初始化地图
    private void initMapView(){

        BitmapDrawable bitmapDrawable = (BitmapDrawable) ContextCompat.getDrawable(MeasureLineActivity.this, R.drawable.icon_measure_point);
        PictureMarkerSymbol locationMarker = new PictureMarkerSymbol(bitmapDrawable);
        locationMarker.setOffsetY(13);

        endLocation = new Graphic();
        endLocation.setSymbol(locationMarker);
        graphicsOverlay.getGraphics().add(endLocation);

        path = new Graphic();
        path.setSymbol(new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, getResources().getColor(R.color.colorWhite), 1));
        graphicsOverlay.getGraphics().add(path);
    }

    @Override
    protected void loadDataFromServer() {

    }

    private void setupMap() {
        if (mMapView != null) {
            ArcGISRuntimeEnvironment.setLicense(CommonKey.LICENSE);
            mMapView.setAttributionTextVisible(false);
            Basemap.Type basemapType = Basemap.Type.IMAGERY;
            ArcGISMap map = new ArcGISMap(basemapType, SystemConfig.latitude, SystemConfig.longitude, SystemConfig.mapLevel);
            mMapView.setMap(map);
        }
    }

    @OnClick({R.id.btn_back, R.id.btn_right, R.id.btn_location, R.id.btn_zoom_in , R.id.btn_zoom_out })
    public void onClick(View v) {
        if (ClickUtils.isFastClick()) { //防止重复点击
            switch (v.getId()) {

                //返回
                case R.id.btn_back:
                    finish();
                    break;

                //清空
                case R.id.btn_right:
                    start = null;
                    //清空图形
                    graphicsOverlay.getGraphics().clear();

                    //初始化地图
                    initMapView();

                    //去掉标记
                    mMapView.getCallout().dismiss();
                    break;

                //定位
                case R.id.btn_location:
                    setupLocationDisplay(true);
                    break;

                //地图放大
                case R.id.btn_zoom_in:
                    mMapView.setViewpointScaleAsync(mMapView.getMapScale() * 0.5);
                    break;

                //地图缩小
                case R.id.btn_zoom_out:
                    mMapView.setViewpointScaleAsync(mMapView.getMapScale() * 2);
                    break;

                default:
                    break;
            }
        }
    }

    private void setupLocationDisplay(boolean boo) {
        mLocationDisplay = mMapView.getLocationDisplay();
        mLocationDisplay.startAsync();

        mLocationDisplay.addLocationChangedListener(new LocationDisplay.LocationChangedListener() {
            @Override
            public void onLocationChanged(LocationDisplay.LocationChangedEvent locationChangedEvent) {
                LocationDataSource.Location location=locationChangedEvent.getLocation();
                Point point=location.getPosition();
                Log.i(TAG, "定位===》"+point.toString());

                if (boo){
                    // center on tapped point
                    mMapView.setViewpointCenterAsync(point,SystemConfig.mapScale);
                }

                mLocationDisplay.removeLocationChangedListener(this);
            }
        });
    }

    @Override
    public void onSuccess(Object model, int tag, String msg) {

    }

    @Override
    public void onError(int errcode, int tag, String message) {

    }

    @Override
    public void onPause() {
        super.onPause();
        // pause MapView
        mMapView.pause();
    }

    @Override
    public void onResume() {
        super.onResume();
        // resume MapView
        mMapView.resume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // dispose MapView
        mMapView.dispose();
    }
}
